<template>
  <div class="student-homework-container">
    <!-- 页面标题 -->
    <div class="page-title">我的作业</div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <el-select v-model="statusFilter" placeholder="作业状态" @change="handleStatusChange">
        <el-option label="全部作业" value="all"></el-option>
        <el-option label="未完成" value="unfinished"></el-option>
        <el-option label="已完成" value="finished"></el-option>
      </el-select>
      <el-select v-model="subjectFilter" placeholder="作业科目" @change="handleSubjectChange">
        <el-option label="全部科目" value="all"></el-option>
        <el-option label="语文" value="chinese"></el-option>
        <el-option label="数学" value="math"></el-option>
        <el-option label="英语" value="english"></el-option>
        <el-option label="科学" value="science"></el-option>
      </el-select>
    </div>

    <!-- 作业列表 -->
    <el-table 
      :data="filteredHomeworks" 
      border 
      style="width: 100%; margin-top: 20px"
      :empty-text="loading ? '加载中...' : '暂无作业'"
    >
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="title" label="作业名称" min-width="200"></el-table-column>
      <el-table-column prop="subject" label="科目">
        <template #default="scope">
          <el-tag :type="getSubjectTagType(scope.row.subject)" effect="plain">
            {{ formatSubject(scope.row.subject) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignDate" label="布置时间"></el-table-column>
      <el-table-column prop="dueDate" label="截止时间">
        <template #default="scope">
          <span :class="isDeadlineNear(scope.row.dueDate) ? 'deadline-warning' : ''">
            {{ scope.row.dueDate }}
            <span v-if="isDeadlineNear(scope.row.dueDate)" class="urgent-mark">!</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag 
            :type="scope.row.submissionStatus === '已完成' ? 'success' : 'warning'"
            :effect="scope.row.submissionStatus === '已完成' ? 'dark' : 'light'"
          >
            {{ scope.row.submissionStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button 
            size="small" 
            @click="viewHomeworkDetails(scope.row)"
          >
            查看详情
          </el-button>
          <el-button 
            size="small" 
            type="primary"
            @click="handleSubmitHomework(scope.row)"
            v-if="scope.row.submissionStatus !== '已完成'"
          >
            提交作业
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 作业详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="作业详情" 
      :width="isMobile ? '90%' : '700px'"
      :close-on-click-modal="false"
    >
      <div v-if="currentHomework" class="homework-detail">
        <div class="detail-header">
          <h3 class="detail-title">{{ currentHomework.title }}</h3>
          <el-tag :type="getSubjectTagType(currentHomework.subject)" effect="plain">
            {{ formatSubject(currentHomework.subject) }}
          </el-tag>
        </div>
        
        <div class="detail-meta">
          <div class="meta-item">
            <span class="meta-label">布置时间：</span>
            <span>{{ currentHomework.assignDate }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">截止时间：</span>
            <span :class="isDeadlineNear(currentHomework.dueDate) ? 'deadline-warning' : ''">
              {{ currentHomework.dueDate }}
            </span>
          </div>
          <div class="meta-item">
            <span class="meta-label">总分：</span>
            <span>{{ currentHomework.totalScore }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">我的状态：</span>
            <el-tag 
              :type="currentHomework.submissionStatus === '已完成' ? 'success' : 'warning'"
            >
              {{ currentHomework.submissionStatus }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-section">
          <h4 class="section-title">作业要求</h4>
          <div class="section-content">{{ currentHomework.homeworkRequire }}</div>
        </div>
        
        <div class="detail-section">
          <h4 class="section-title">作业内容</h4>
          <div class="section-content">{{ currentHomework.content }}</div>
        </div>
        
        <div v-if="currentHomeworkFiles.length > 0" class="detail-section">
          <h4 class="section-title">作业附件</h4>
          <div class="file-list">
            <div v-for="file in currentHomeworkFiles" :key="file.id" class="file-item">
              <el-link :href="file.filePath" target="_blank">
                <el-icon class="file-icon"><Document /></el-icon>
                <span class="file-name">{{ file.fileName }}</span>
                <span class="file-size">({{ formatFileSize(file.fileSize) }})</span>
              </el-link>
            </div>
          </div>
        </div>
        
        <!-- 提交记录 -->
        <div v-if="currentHomework.submissionStatus === '已完成' && currentSubmission" class="detail-section">
          <h4 class="section-title">我的提交</h4>
          <div class="submission-info">
            <div class="submission-item">
              <span class="meta-label">提交时间：</span>
              <span>{{ currentSubmission.submitTime }}</span>
            </div>
            <div class="submission-item" v-if="currentSubmission.score !== null">
              <span class="meta-label">得分：</span>
              <span class="score">{{ currentSubmission.score }} / {{ currentHomework.totalScore }}</span>
            </div>
            <div class="submission-item" v-if="currentSubmission.teacherComment">
              <span class="meta-label">教师评语：</span>
              <span>{{ currentSubmission.teacherComment }}</span>
            </div>
          </div>
          
          <div v-if="currentSubmissionFiles.length > 0" class="submission-files">
            <h5 class="files-title">提交文件：</h5>
            <div class="file-list">
              <div v-for="file in currentSubmissionFiles" :key="file.id" class="file-item">
                <el-link :href="file.filePath" target="_blank">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <span class="file-name">{{ file.fileName }}</span>
                  <span class="file-size">({{ formatFileSize(file.fileSize) }})</span>
                </el-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 提交作业弹窗 -->
    <el-dialog 
      v-model="submitDialogVisible" 
      title="提交作业" 
      :width="isMobile ? '90%' : '600px'"
      :close-on-click-modal="false"
    >
      <div v-if="currentHomework" class="submit-homework-form">
        <el-form ref="submitFormRef" :model="submitForm" label-width="80px">
          <el-form-item label="作业名称" disabled>
            <el-input v-model="currentHomework.title"></el-input>
          </el-form-item>
          
          <el-form-item label="作业内容" prop="submissionContent">
            <el-input 
              v-model="submitForm.submissionContent" 
              type="textarea" 
              rows="4" 
              placeholder="请输入作业完成情况描述"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="上传附件">
            <el-upload 
              class="upload-demo" 
              :file-list="uploadFiles" 
              :limit="5"
              :auto-upload="false" 
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              multiple
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传 doc, docx, pdf, jpg, png 格式文件，单个文件不超过10MB，最多5个
                </div>
              </template>
            </el-upload>
            
            <!-- 上传进度显示 -->
            <div v-if="uploadProgress.visible" class="upload-progress">
              <el-progress 
                :percentage="uploadProgress.percentage" 
                :status="uploadProgress.status"
                :text-inside="true" 
                :stroke-width="20"
              />
              <div class="progress-info">{{ uploadProgress.info }}</div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmSubmit"
          :loading="submitting"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue';
import {
  insertHomeworkResult,
  getHomeworkResult,
  getHomeworkProblemByClassId,
  getHomeworkProblemFileByProblemId,
  getHomeworkResultFileByResultId
} from '../../../api/homework/homework.js';
import { ElMessage, ElLoading, columnAlignment } from 'element-plus';
import { useLoginStore } from '../../../stores/index.js'; // 假设存在登录状态管理

// 状态管理
const loginStore = useLoginStore();
const studentNum = "student1"; // 学生学号
const classId = 1; // 学生班级ID

// 加载状态
const loading = ref(true);
const submitting = ref(false);

// 筛选条件
const statusFilter = ref('all');
const subjectFilter = ref('all');

// 作业数据
const allHomeworks = ref([]);
const filteredHomeworks = ref([]);

// 弹窗控制
const detailDialogVisible = ref(false);
const submitDialogVisible = ref(false);
const currentHomework = ref(null);
const currentSubmission = ref(null);
const currentHomeworkFiles = ref([]);
const currentSubmissionFiles = ref([]);

// 提交表单数据
const submitForm = reactive({
  submissionContent: ''
});

// 上传文件相关
const uploadFiles = ref([]);
const uploadProgress = reactive({
  visible: false,
  percentage: 0,
  status: 'success',
  info: ''
});

// 响应式判断是否为移动设备
const isMobile = ref(window.innerWidth <= 768);

// 监听窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768;
};

// 初始化页面
onMounted(async () => {
    fetchHomeworks();
});

// 获取作业列表
const fetchHomeworks = async () => {
  try {
    loading.value = true;
    const response = await getHomeworkProblemByClassId(classId);
    
    if (response && Array.isArray(response)) {
      allHomeworks.value = response;
      // 为每个作业添加提交状态
      for (const homework of allHomeworks.value) {
        await checkHomeworkStatus(homework);
      }
      filterHomeworks();
    }
  } catch (error) {
    ElMessage.error('获取作业列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 检查作业提交状态
const checkHomeworkStatus = async (homework) => {
  try {
    const response = await getHomeworkResult(homework.id, studentNum);
    homework.submissionStatus = response ? '已完成' : '未完成';
    homework.submissionId = response?.id;
  } catch (error) {
    console.error(`检查作业[${homework.id}]状态失败:`, error);
    homework.submissionStatus = '未完成';
  }
};

// 筛选作业
const filterHomeworks = () => {
  filteredHomeworks.value = allHomeworks.value.filter(homework => {
    // 状态筛选
    if (statusFilter.value !== 'all') {
      const targetStatus = statusFilter.value === 'finished' ? '已完成' : '未完成';
      if (homework.submissionStatus !== targetStatus) {
        return false;
      }
    }
    
    // 科目筛选
    if (subjectFilter.value !== 'all' && homework.subject !== subjectFilter.value) {
      return false;
    }
    
    return true;
  });
};

// 处理状态筛选变化
const handleStatusChange = () => {
  filterHomeworks();
};

// 处理科目筛选变化
const handleSubjectChange = () => {
  filterHomeworks();
};

// 查看作业详情
const viewHomeworkDetails = async (homework) => {
  try {
    currentHomework.value = { ...homework };
    currentHomeworkFiles.value = [];
    currentSubmission.value = null;
    currentSubmissionFiles.value = [];
    
    // 获取作业附件
    const fileResponse = await getHomeworkProblemFileByProblemId(homework.id);
    if (fileResponse && Array.isArray(fileResponse)) {
      currentHomeworkFiles.value = fileResponse;
    }
    
    // 如果已提交，获取提交内容和附件
    if (homework.submissionStatus === '已完成' && homework.submissionId) {
      const submissionResponse = await getHomeworkResult(homework.id, studentNum);
      if (submissionResponse) {
        currentSubmission.value = submissionResponse;
        
        // 获取提交的附件
        const submissionFileResponse = await getHomeworkResultFileByResultId(homework.submissionId);
        if (submissionFileResponse && Array.isArray(submissionFileResponse)) {
          currentSubmissionFiles.value = submissionFileResponse;
        }
      }
    }
    
    detailDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取作业详情失败');
    console.error(error);
  }
};

// 处理提交作业
const handleSubmitHomework = (homework) => {
  currentHomework.value = { ...homework };
  submitForm.submissionContent = '';
  uploadFiles.value = [];
  submitDialogVisible.value = true;
};

const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 确认提交
const confirmSubmit = async () => {
  if (!currentHomework.value) return;
  
  try {
    submitting.value = true;
    uploadProgress.visible = true;
    uploadProgress.percentage = 0;
    uploadProgress.status = 'success';
    uploadProgress.info = '开始上传...';
    
    // 准备提交数据
const resultData = {
  homeworkProblemId: currentHomework.value.id,
  studentNum: studentNum,
  submissionContent: submitForm.submissionContent
};
    
    // 准备文件数据
    const files = uploadFiles.value.map(file => file.raw);
    
    // 调用API提交
    const response = await insertHomeworkResult(resultData, files);
    
    if (response == 1) {
      uploadProgress.percentage = 100;
      uploadProgress.info = '上传完成';
      ElMessage.success('作业提交成功');
      
      // 更新作业状态
      const homeworkIndex = allHomeworks.value.findIndex(h => h.id === currentHomework.value.id);
      if (homeworkIndex !== -1) {
        allHomeworks.value[homeworkIndex].submissionStatus = '已完成';
      }
      filterHomeworks();
      
      submitDialogVisible.value = false;
    } else {
     uploadProgress.status = 'exception';
      uploadProgress.info = '上传失败';
      ElMessage.error(response?.message || '作业提交失败');
    }
  } catch (error) {
    uploadProgress.status = 'exception';
    uploadProgress.info = '上传失败';
    ElMessage.error('提交失败，请重试');
    console.error(error);
  } finally {
    submitting.value = false;
    setTimeout(() => {
      uploadProgress.visible = false;
    }, 2000);
  }
};

// 文件上传相关方法
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList;
};

const handleFileRemove = (file, fileList) => {
  uploadFiles.value = fileList;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传5个文件，当前选择了 ${files.length} 个文件，共 ${files.length + fileList.length} 个文件`);
};

const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB');
    return false;
  }
  
  const allowedTypes = ['doc', 'docx', 'pdf', 'jpg', 'jpeg', 'png'];
  const fileType = file.name.split('.').pop().toLowerCase();
  if (!allowedTypes.includes(fileType)) {
    ElMessage.error('只支持上传 doc, docx, pdf, jpg, png 格式的文件');
    return false;
  }
  
  return true;
};

// 工具方法：格式化科目显示
const formatSubject = (subject) => {
  const subjectMap = {
    'chinese': '语文',
    'math': '数学',
    'english': '英语',
    'science': '科学'
  };
  return subjectMap[subject] || subject;
};

// 工具方法：获取科目标签类型
const getSubjectTagType = (subject) => {
  const typeMap = {
    'chinese': 'danger',
    'math': 'primary',
    'english': 'success',
    'science': 'warning'
  };
  return typeMap[subject] || 'info';
};

// 工具方法：判断是否即将截止（2天内）
const isDeadlineNear = (deadline) => {
  if (!deadline) return false;
  
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  const deadlineDate = new Date(deadline);
  deadlineDate.setHours(0, 0, 0, 0);
  
  const diffTime = deadlineDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  return diffDays >= 0 && diffDays <= 2;
};

// 工具方法：格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === null || bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>

<style scoped>
.student-homework-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.filter-bar .el-select {
  width: 180px;
}

.deadline-warning {
  color: #f56c6c;
  font-weight: bold;
}

.urgent-mark {
  display: inline-block;
  color: #f56c6c;
  margin-left: 5px;
  animation: blink 1s infinite;
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0; }
  100% { opacity: 1; }
}

.homework-detail {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
  margin-bottom: 20px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  color: #999;
  margin-right: 5px;
}

.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.section-content {
  padding-left: 12px;
  line-height: 1.6;
  color: #666;
}

.file-list {
  padding-left: 12px;
}

.file-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  color: #409eff;
}

.file-name {
  margin-right: 10px;
}

.file-size {
  color: #999;
  font-size: 12px;
}

.submission-info {
  margin-bottom: 15px;
  padding-left: 12px;
}

.submission-item {
  margin-bottom: 8px;
}

.score {
  color: #e6a23c;
  font-weight: bold;
}

.submit-homework-form {
  padding: 10px 0;
}

.upload-progress {
  margin-top: 15px;
}

.progress-info {
  text-align: center;
  margin-top: 5px;
  color: #666;
}

@media (max-width: 768px) {
  .student-homework-container {
    padding: 10px;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 10px;
  }
  
  .filter-bar .el-select {
    width: 100%;
  }
  
  .detail-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .meta-item {
    width: 100%;
  }
}
</style>